/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package co.edo.unal.telemedicina.data;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author lariverosc
 */
public class ExtractData {

    //
    private static String outPath = "/home/lariverosc/data/saruro/";

    /**
     * This method is used to extract the path of the images associated with a case of a particular especialty,
     * the output data is stored in a file called <b>spcode<\b>+actID-images.txt in the outPath directory.
     * @param String spcode the specialty code
     * @return nothing
     */
    public static void extractImages(String spcode) {
        try {
            ExtractDataDAO extractDataDAO = new ExtractDataDAO();
            extractDataDAO.connect();
            extractDataDAO.init();
            List<String> actIDs = extractDataDAO.getCaseIDsBySpecialty(spcode);
            File file = new File(outPath + spcode + "-actID-images.txt");
            FileWriter fileWriter;
            fileWriter = new FileWriter(file);
            BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
            List<String> images;
            for (String actID : actIDs) {
                images = extractDataDAO.listRelatedDiagnosticImages(actID);
                for (String image : images) {
                    bufferedWriter.write(actID + " " + image + "\n");
                }
            }
            bufferedWriter.flush();
            bufferedWriter.close();
            extractDataDAO.disconnect();
        } catch (FileNotFoundException ex) {
            Logger.getLogger(ExtractData.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(ExtractData.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(ExtractData.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    public static void extractImageText(String imgNamesPath) {
        try {
            File file1 = new File(imgNamesPath);
            FileReader fileReader = new FileReader(file1);
            BufferedReader bufferedReader = new BufferedReader(fileReader);
            List<String> imageNames = new ArrayList<String>();
            String lineIn, lineOut;
            while ((lineIn = bufferedReader.readLine()) != null) {
                imageNames.add(lineIn);
            }
            bufferedReader.close();
            ExtractDataDAO extractDataDAO = new ExtractDataDAO();
            extractDataDAO.connect();
            extractDataDAO.init();
            String mainActID;
            String imageActID;
            String patientRol, doctorRol, agentRol;
            String notAnom;
            String anom;

            List<String> tempActIDs;
            List<String> tempActIDs2;
            File file2;
            FileWriter fileWriter;
            BufferedWriter bufferedWriter;
            Hashtable<String, String> tempInfo;
            for (String image : imageNames) {
                file2 = new File(outPath + image + ".txt");
                if (!file2.exists()) {
                    file2.createNewFile();
                }
                fileWriter = new FileWriter(file2);
                bufferedWriter = new BufferedWriter(fileWriter);
                imageActID = extractDataDAO.getImageActID(image);
                mainActID = extractDataDAO.getAssociatedAct(imageActID);
                System.out.println(mainActID);
                bufferedWriter.write("###############Información del paciente\n");
                patientRol = extractDataDAO.getRelatedPatientRole(mainActID);
                tempInfo = extractDataDAO.listPersonalInformation(patientRol);
                //bufferedWriter.write("**Document: " + tempInfo.get("document") + "\n");
                //bufferedWriter.write("**Nombre: " + tempInfo.get("name") + "\n");
                bufferedWriter.write("Genero: " + tempInfo.get("administrativegendercode") + "\n");
//                bufferedWriter.write("**Fecha de nacimiento: " + tempInfo.get("beginexistencetime") + "\n");
//                bufferedWriter.write("**Teléfono: " + tempInfo.get("telecom") + "\n");
//                bufferedWriter.write("**Dirección: " + tempInfo.get("addr") + "\n");
//                bufferedWriter.write("**Descripción: " + tempInfo.get("description") + "\n");
//                bufferedWriter.write("Tipo de sangre: " + tempInfo.get("bloodtype") + "\n");
//                bufferedWriter.write("Estado civil: " + tempInfo.get("maritalstatuscode") + "\n");
//                bufferedWriter.write("Nivel de educación: " + tempInfo.get("educationLevelcode") + "\n");

                bufferedWriter.write("###############Información del doctor\n");
                doctorRol = extractDataDAO.getRelatedDoctorRole(mainActID);
                tempInfo = extractDataDAO.listPersonalInformation(doctorRol);

//                bufferedWriter.write("**Document: " + tempInfo.get("document") + "\n");
                //bufferedWriter.write("**Nombre: " + tempInfo.get("name") + "\n");
//                bufferedWriter.write("Genero: " + tempInfo.get("administrativegendercode") + "\n");
//                bufferedWriter.write("**Fecha de nacimiento: " + tempInfo.get("beginexistencetime") + "\n");
//                bufferedWriter.write("**Teléfono: " + tempInfo.get("telecom") + "\n");
//                bufferedWriter.write("**Dirección: " + tempInfo.get("addr") + "\n");
//                bufferedWriter.write("**Descripción: " + tempInfo.get("description") + "\n");
//                bufferedWriter.write("Tipo de sangre: " + tempInfo.get("bloodtype") + "\n");
//                bufferedWriter.write("Estado civil: " + tempInfo.get("maritalstatuscode") + "\n");
//                bufferedWriter.write("Nivel de educación: " + tempInfo.get("educationLevelcode") + "\n");

                bufferedWriter.write("###############Información del agente\n");
                agentRol = extractDataDAO.getRelatedAgentRole(mainActID);
                tempInfo = extractDataDAO.listPersonalInformation(agentRol);
                bufferedWriter.write("**Document: " + tempInfo.get("document") + "\n");
                //  bufferedWriter.write("**Nombre: " + tempInfo.get("name") + "\n");
//                bufferedWriter.write("Genero: " + tempInfo.get("administrativegendercode") + "\n");
//                bufferedWriter.write("**Fecha de nacimiento: " + tempInfo.get("beginexistencetime") + "\n");
//                bufferedWriter.write("**Teléfono: " + tempInfo.get("telecom") + "\n");
//                bufferedWriter.write("**Dirección: " + tempInfo.get("addr") + "\n");
//                bufferedWriter.write("**Descripción: " + tempInfo.get("description") + "\n");
//                bufferedWriter.write("Tipo de sangre: " + tempInfo.get("bloodtype") + "\n");
//                bufferedWriter.write("Estado civil: " + tempInfo.get("maritalstatuscode") + "\n");
//                bufferedWriter.write("Nivel de educación: " + tempInfo.get("educationLevelcode") + "\n");

                bufferedWriter.write("###############Información del caso\n");
                tempInfo = extractDataDAO.listCaseInformation(mainActID);
                bufferedWriter.write("Título: " + tempInfo.get("title") + "\n");
                bufferedWriter.write("Descripción: " + tempInfo.get("text") + "\n");

                bufferedWriter.write("###############Información de las observaciones\n");
                tempActIDs = extractDataDAO.listRelatedObservations(mainActID);
                int count = 1;
                for (String actID : tempActIDs) {
                    tempInfo = extractDataDAO.listObservationInformation(actID);
                    bufferedWriter.write("$$$$$$$$$$Observación$$$$$$$$$$ " + count + ":\n");
                    bufferedWriter.write("Título: " + tempInfo.get("title") + "\n");
                    bufferedWriter.write("Descripción: " + tempInfo.get("text") + "\n");
                    bufferedWriter.write("Motívo: " + tempInfo.get("reasonCode") + "\n");
                    bufferedWriter.write("Valor: " + tempInfo.get("value") + "\n");
                    bufferedWriter.write("Interpretación: " + tempInfo.get("interpretationCode") + "\n");
                    bufferedWriter.write("Método: " + tempInfo.get("methodCode") + "\n");
                    bufferedWriter.write("Sitio: " + tempInfo.get("targetSiteCode") + "\n");
                    tempActIDs2 = extractDataDAO.listRelatedObservations(actID);
                    for (String actID2 : tempActIDs) {
                        bufferedWriter.write("$$$$$$$$$$Observación$$$$$$$$$$ " + count + ":\n");
                        tempInfo = extractDataDAO.listObservationInformation(actID2);
                        bufferedWriter.write("Título: " + tempInfo.get("title") + "\n");
                        bufferedWriter.write("Descripción: " + tempInfo.get("text") + "\n");
                        bufferedWriter.write("Motívo: " + tempInfo.get("reasonCode") + "\n");
                        bufferedWriter.write("Valor: " + tempInfo.get("value") + "\n");
                        bufferedWriter.write("Interpretación: " + tempInfo.get("interpretationCode") + "\n");
                        bufferedWriter.write("Método: " + tempInfo.get("methodCode") + "\n");
                        bufferedWriter.write("Sitio: " + tempInfo.get("targetSiteCode") + "\n");
                        count++;
                    }
                    count++;
                }
                bufferedWriter.flush();
                bufferedWriter.close();
            }
            extractDataDAO.disconnect();

            //Remove names

        } catch (FileNotFoundException ex) {
            Logger.getLogger(ExtractData.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(ExtractData.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(ExtractData.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    public static void buildXMLFromSaruro() throws SQLException {
        List<String> specialtyList, caseIDs, observationsIDs, subActsIDs, imagesIDs, mprotIDS, answersIDs, cies, entrys;
        String specialtyName, patientID, doctorID, specialistID;
        Hashtable<String, String> caseInfo, personalInfo, observationInfo, imageInfo, answerInfo, entryInfo;
        ExtractDataDAO extractDataDAO = new ExtractDataDAO();
        extractDataDAO.setAnonymize(true);
        extractDataDAO.connect();
        extractDataDAO.init();
        specialtyList = extractDataDAO.listSpecialtyIDS();
        TableDocument documentXML;
        int nameCount = 1, obsCount, imageCount, answerCount, cieCount, entryCount;
        for (String spcode : specialtyList) {
            specialtyName = extractDataDAO.getSpecialtyName(spcode);
            caseIDs = extractDataDAO.getCaseIDsBySpecialty(spcode);
            for (String caseID : caseIDs) {
                System.out.println("Case " + caseID);
                obsCount = imageCount = answerCount = cieCount = entryCount = 1;
                documentXML = new TableDocument("Case");
                documentXML.addTagContent("specialty", specialtyName);
                documentXML.addTagContent("case_id", caseID);
                caseInfo = extractDataDAO.listCaseInformation(caseID);
                documentXML.addContentWithPrefix("case", caseInfo);
                //Participations
                patientID = extractDataDAO.getRelatedPatientRole(caseID);
                personalInfo = extractDataDAO.listPersonalInformation(patientID);
                documentXML.addContentWithPrefix("patient", personalInfo);
                doctorID = extractDataDAO.getRelatedDoctorRole(caseID);
                personalInfo = extractDataDAO.listPersonalInformation(doctorID);
                documentXML.addContentWithPrefix("doctor", personalInfo);

                //Related acts
                //Observations and measures
                observationsIDs = extractDataDAO.listRelatedObservations(caseID);
                for (String observationID : observationsIDs) {
                    observationInfo = extractDataDAO.listObservationInformation(observationID);
                    documentXML.addContentWithPrefix("observation-" + obsCount, observationInfo);
                    obsCount++;
                    if (extractDataDAO.hasRelatedActs(observationID)) {
                        subActsIDs = extractDataDAO.listRelatedObservations(observationID);
                        for (String subActID : subActsIDs) {
                            observationInfo = extractDataDAO.listObservationInformation(subActID);
                            documentXML.addContentWithPrefix("observation-" + obsCount, observationInfo);
                            obsCount++;
                        }
                    }
                }

                //Diagnostic images
                imagesIDs = extractDataDAO.listRelatedDiagnosticImages(caseID);
                for (String imageID : imagesIDs) {
                    imageInfo = extractDataDAO.listDiagnosticImageInformation(imageID);
                    documentXML.addContentWithPrefix("image-" + imageCount, imageInfo);
                    imageCount++;
                }

                //Monitoring acts
                mprotIDS = extractDataDAO.listMonitoring(caseID);
                for (String mprot : mprotIDS) {
                    observationInfo = extractDataDAO.listObservationInformation(mprot);
                    documentXML.addContentWithPrefix("observation-" + obsCount, observationInfo);
                    obsCount++;
                    if (extractDataDAO.hasRelatedActs(mprot)) {
                        subActsIDs = extractDataDAO.listRelatedObservations(mprot);
                        for (String subActID : subActsIDs) {
                            observationInfo = extractDataDAO.listObservationInformation(subActID);
                            documentXML.addContentWithPrefix("observation-" + obsCount, observationInfo);
                            obsCount++;
                        }
                    }
                }

                //Answers to case
                answersIDs = extractDataDAO.listRelatedAnswers(caseID);
                for (String answerID : answersIDs) {
                    specialistID = extractDataDAO.getRelatedSpecialistRole(answerID);
                    personalInfo = extractDataDAO.listPersonalInformation(specialistID);
                    documentXML.addContentWithPrefix("specialist", personalInfo);
                    answerInfo = extractDataDAO.listAnswerInformation(answerID);
                    documentXML.addContentWithPrefix("answer-" + answerCount, answerInfo);
                    answerCount++;
                    entrys = extractDataDAO.listRelatedEntry(answerID);
                    for (String entry : entrys) {
                        documentXML.addTagContent("entry-" + entryCount, entry);
                        entryCount++;
                    }
                    //Related cies
                    cies = extractDataDAO.listRelatedCIE(answerID);
                    for (String cie : cies) {
                        documentXML.addTagContent("cie-" + cieCount, cie);
                        cieCount++;
                    }
                }
                nameCount++;
                //Save the document
                XMLDOM.saveXMLFile("/home/lariverosc/saruroData/", documentXML);
            }
        }
        extractDataDAO.disconnect();
    }

    public static void extractText() throws SQLException {
        List<String> specialtyList, caseIDs, observationsIDs, subActsIDs, imagesIDs, mprotIDS, answersIDs, cies, entrys;
        String specialtyName, patientID, doctorID, specialistID, observationGroup;
        Hashtable<String, String> caseInfo, personalInfo, observationInfo, imageInfo, answerInfo;
        ExtractDataDAO extractDataDAO = new ExtractDataDAO();
        extractDataDAO.setAnonymize(true);
        extractDataDAO.connect();
        extractDataDAO.init();
        specialtyList = extractDataDAO.listSpecialtyIDS();
        DocumentXML documentXML;
        int nameCount = 1, imageCount, answerCount, cieCount, entryCount;
        for (String spcode : specialtyList) {//For each specialty
            specialtyName = extractDataDAO.getSpecialtyName(spcode);//get specialty name
            caseIDs = extractDataDAO.getCaseIDsBySpecialty(spcode); //get cases by specialty
            for (String caseID : caseIDs) {//For each case
                System.out.println("caso " + caseID);
                imageCount = answerCount = cieCount = entryCount = 1;
                documentXML = new DocumentXML(new NodeXML("caso"));
                documentXML.add("caso", "especialidad", specialtyName);//Add specialty
                documentXML.add("caso", "id", caseID);//Add act Id      
                caseInfo = extractDataDAO.listCaseInformation(caseID);
                documentXML.add("caso", caseInfo);
                //Participations
                patientID = extractDataDAO.getRelatedPatientRole(caseID);//get PatientId
                personalInfo = extractDataDAO.listPersonalInformation(patientID);//get Patient personal information
                documentXML.add("caso" + DocumentXML.XML_PATH_SEPARATOR + "paciente", personalInfo);
                doctorID = extractDataDAO.getRelatedDoctorRole(caseID);//get doctorId personal information
                personalInfo = extractDataDAO.listPersonalInformation(doctorID);
                documentXML.add("caso" + DocumentXML.XML_PATH_SEPARATOR + "medico", personalInfo);

                //Related acts
                //Observations and measures
                observationsIDs = extractDataDAO.listRelatedObservations(caseID);

                for (String observationID : observationsIDs) {
                    observationGroup = "";
                    observationInfo = extractDataDAO.listObservationInformation(observationID);
                    if (observationInfo.get("texto").length() == 0 && observationInfo.get("valor").length() == 0) {
                        observationGroup = observationInfo.get("titulo");
                    } else {
                        documentXML.add("caso" + DocumentXML.XML_PATH_SEPARATOR + "observation", observationInfo);
                    }
                    if (extractDataDAO.hasRelatedActs(observationID)) {
                        subActsIDs = extractDataDAO.listRelatedObservations(observationID);
                        for (String subActID : subActsIDs) {
                            observationInfo = extractDataDAO.listObservationInformation(subActID);
                            documentXML.add("caso" + DocumentXML.XML_PATH_SEPARATOR + observationGroup, observationInfo.get("titulo"), observationInfo.get("valor") + " " + observationInfo.get("texto"));
                        }
                    }
                }

                //Diagnostic images
                imagesIDs = extractDataDAO.listRelatedDiagnosticImages(caseID);
                for (String imageID : imagesIDs) {
                    imageInfo = extractDataDAO.listDiagnosticImageInformation(imageID);
//                    documentXML.add("caso" + DocumentXML.XML_PATH_SEPARATOR + "imagen-" + imageCount, imageInfo);
                    imageCount++;
                }

                //Monitoring acts
                mprotIDS = extractDataDAO.listMonitoring(caseID);
                for (String mprot : mprotIDS) {
                    if (extractDataDAO.hasRelatedActs(mprot)) {
                        subActsIDs = extractDataDAO.listRelatedObservations(mprot);
                        for (String subActID : subActsIDs) {
                            observationInfo = extractDataDAO.listObservationInformation(subActID);
                            documentXML.add("caso" + DocumentXML.XML_PATH_SEPARATOR + "monitoreo", observationInfo);
                        }
                    }
                }

                //Answers to case
                answersIDs = extractDataDAO.listRelatedAnswers(caseID);
                for (String answerID : answersIDs) {
                    specialistID = extractDataDAO.getRelatedSpecialistRole(answerID);
                    personalInfo = extractDataDAO.listPersonalInformation(specialistID);
                    documentXML.add("caso" + DocumentXML.XML_PATH_SEPARATOR + "respuesta-" + answerCount + DocumentXML.XML_PATH_SEPARATOR + "especialista", personalInfo);
                    answerInfo = extractDataDAO.listAnswerInformation(answerID);
                    documentXML.add("caso" + DocumentXML.XML_PATH_SEPARATOR + "respuesta-" + answerCount, answerInfo);
                    answerCount++;
                    entrys = extractDataDAO.listRelatedEntry(answerID);
                    for (String entry : entrys) {
                        documentXML.add("caso" + DocumentXML.XML_PATH_SEPARATOR + "respuesta-" + answerCount, "entrada-" + entryCount, entry);
                        entryCount++;
                    }
                    //Related cies
                    cies = extractDataDAO.listRelatedCIE(answerID);
                    for (String cie : cies) {
//                        documentXML.add("caso" + DocumentXML.XML_PATH_SEPARATOR + "respuesta-" + answerCount, "cie-" + cieCount, cie);
                        cieCount++;
                    }
                }
                nameCount++;
//                Save the document
                StoreDocument.saveTXTFile("D:\\AAA\\saruroData2TXT\\", documentXML);
            }
        }
        extractDataDAO.disconnect();
    }

    public static void extractCie(String inPath, String outPath) throws IOException, SQLException {
        File file = new File(inPath);
        FileReader fileReader = new FileReader(file);
        BufferedReader bufferedReader = new BufferedReader(fileReader);
        List<String> caseIDs = new ArrayList<String>();
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            caseIDs.add(line.substring(0, line.lastIndexOf(".")));
        }
        bufferedReader.close();

        ExtractDataDAO extractDataDAO = new ExtractDataDAO();
        extractDataDAO.connect();
        extractDataDAO.init();
        List<String> answerIDs;
        List<String> cies;
        file = new File(outPath);
        FileWriter fileWriter = new FileWriter(file);
        BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
        System.out.println(caseIDs.size() + " Cases");
        for (String caseId : caseIDs) {
            try {
                answerIDs = extractDataDAO.listRelatedAnswers(caseId);
                if (answerIDs.size() > 0) {
                    cie:
                    for (int i = 0; i < answerIDs.size(); i++) {
                        cies = extractDataDAO.listRelatedCIE(answerIDs.get(i));
                        if (cies.size() > 0) {
                            System.out.println(caseId + " - " + cies.get(0));
                            bufferedWriter.write(cies.get(0) + "\n".replace(" ", "_"));
                            break cie;
                        } else if (i == answerIDs.size() - 1) {
                            System.out.println(caseId + " - SIN RESPUESTA");
                            bufferedWriter.write("SIN_RESPUESTA\n");
                        }
                    }
                } else {
                    System.out.println(caseId + " - SIN RESPUESTA");
                    bufferedWriter.write("SIN_RESPUESTA\n");
                }
            } catch (Exception e) {
                System.out.println(caseId + " - unknow");
                bufferedWriter.write("SIN_RESPUESTA\n");
            }
        }
        extractDataDAO.disconnect();
        bufferedWriter.flush();
        bufferedWriter.close();

    }

    public static void extractSpecialtys(String inPath, String outPath) throws IOException, SQLException {
        File file = new File(inPath);
        FileReader fileReader = new FileReader(file);
        BufferedReader bufferedReader = new BufferedReader(fileReader);
        List<String> caseIDs = new ArrayList<String>();
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            caseIDs.add(line.substring(0, line.lastIndexOf(".")));
            System.out.println(line.substring(0, line.lastIndexOf(".")));
        }
        bufferedReader.close();

        file = new File(outPath);
        FileWriter fileWriter = new FileWriter(file);
        BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);

        ExtractDataDAO extractDataDAO = new ExtractDataDAO();
        extractDataDAO.connect();
        extractDataDAO.init();
        for (String caseId : caseIDs) {
            try {
                System.out.println(caseId + " - " + extractDataDAO.getSpecialtyName(extractDataDAO.getSpecialtyForCase(caseId)));
                bufferedWriter.write(extractDataDAO.getSpecialtyName(extractDataDAO.getSpecialtyForCase(caseId)) + "\n".replace(" ", "_"));
            } catch (NullPointerException e) {
                System.out.println("Not cie for " + caseId);
            }
        }
        extractDataDAO.disconnect();
        bufferedWriter.flush();
        bufferedWriter.close();

    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws FileNotFoundException, IOException, SQLException {
        //extractImages("/home/lariverosc/data/imagesPaths.sh", "200");
        //extractText("/home/lariverosc/imgnames.txt");
        extractText();
//        extractSpecialtys("/home/alejandro/Informed/data/SARURO-DocumentList.txt", "/home/alejandro/Informed/data/SaruroSP.txt");
//        extractCie("/home/alejandro/Informed/data/SARURO-DocumentList.txt", "/home/alejandro/Informed/data/SaruroCIE.txt");

    }
}
